package com.cloud.user.listener;

import com.cloud.common.constant.Constants;
import com.cloud.common.utils.JsonUtil;
import com.cloud.common.utils.Mail;
import com.cloud.user.dataobject.UserInfo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class UserQueueListener {

    @Autowired
    private Mail mail;
//    @RabbitListener(queues = Constants.USER_QUEUE_NAME)
//    public void handler(Message message, Channel channel) throws IOException {
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//
//        try{
//            String body = new String(message.getBody());
//            log.info("收到用户消息，body:{}",body);
//
//            channel.basicAck(deliveryTag,true);
//        }catch (Exception e){
//            channel.basicNack(deliveryTag,true,true);
//            log.error("消息发送失败，e:",e);
//        }
//
//    }
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = Constants.USER_QUEUE_NAME,durable = "true"),
        exchange = @Exchange(value = Constants.USER_EXCHANGE_NAME,type = ExchangeTypes.FANOUT)
))
public void handler(Message message, Channel channel) throws IOException {
    long deliveryTag = message.getMessageProperties().getDeliveryTag();

    try{
        String body = new String(message.getBody());
        log.info("收到用户消息，body:{}",body);

        UserInfo userInfo = JsonUtil.parseJson(body, UserInfo.class);
        try {
            mail.send(userInfo.getEmail(), "欢迎加入未梦博客社区", buildContent(userInfo));
        }catch (Exception e){
            log.error("邮件发送失败");
        }
        channel.basicAck(deliveryTag,true);
    }catch (Exception e){
        channel.basicNack(deliveryTag,true,true);
        log.error("消息发送失败，e: ",e);
    }

}
private String buildContent(UserInfo userInfo){
    StringBuilder sb = new StringBuilder();
           sb.append("尊敬的").append(userInfo.getUserName()).append(", 您好! <br/>")
            .append("感谢您注册成为我们博客社区的⼀员! 我们很⾼兴您决定加⼊我们的⼤家庭. <br/>")
            .append("您的注册信息如下: </br/>")
            .append("⽤户名:").append(userInfo.getUserName()).append("<br/>")
            .append("为了确保您的账户安全，请妥善保管您的登录信息. <br/>")
            .append("再次感谢您的加⼊，我们期待看到您的精彩内容！<br/>")
            .append("最好的祝愿<br/>")
            .append("未梦博客团队");
    return sb.toString();

}
}
